package com.donger.business.upms.service.impl;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.donger.common.core.constant.CommonConstants;
import com.donger.common.core.constant.SecurityConstants;
import com.donger.common.core.exception.BizException;
import com.donger.common.data.service.Global;
import com.google.code.kaptcha.Producer;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * 验证码service
 *
 * @author lhl
 */
@Service
@AllArgsConstructor
public class ImagesService {


    private final Producer producer;

    private final RedisTemplate redisTemplate;

    /**
     * 生成验证码
     * TODO 在redis 缓存 并且在mysql 存储一份
     * @param uuid
     * @return
     */
    public BufferedImage getCaptcha(String uuid) {
        if (StrUtil.isBlank(uuid)) {
            throw new BizException("uuid不能为空");
        }
        String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
        String time = Global.getConfig("sys.account.validCodeTimeout", "10");
        // 验证码保存 5 分钟
        redisTemplate.opsForValue().set(CommonConstants.DEFAULT_CAPTCHA_KEY + uuid, code, Long.parseLong(time), TimeUnit.MINUTES);
        return producer.createImage(code);
    }


    /**
     *
     * 验证码校验
     * TODO 先查看缓存 如果没有则查询mysql
     *
     * @param uuid
     * @param code
     * @return
     */
    public boolean validate(String uuid, String code) {
        if (StrUtil.isBlank(uuid)) {
            throw new BizException("uuid不能为空");
        }
        if (StrUtil.isBlank(code)) {
            throw new BizException("验证码不能为空");
        }
        String tempCode = (String) redisTemplate.opsForValue().get(CommonConstants.DEFAULT_CAPTCHA_KEY + uuid);
        if (tempCode == null) {
            throw new BizException("验证码失效");
        }

        // 不管是否验证成功  都要删除验证码
        redisTemplate.delete(CommonConstants.DEFAULT_CAPTCHA_KEY + uuid);
        return code.equals(tempCode);
    }

}
